<style lang="less">
  .driver-manage{
    .el-form{
      .el-cascader{
        width: 100%;
      }
    }
  }
</style>

<template>
  <section class="driver-manage">
    <!--工具条-->
    <search-bar more-display>
      <el-row>
        <el-col :span="8">
          <el-form-item label="司机编号">
            <el-input
                      v-model="searchCondition.LIKE_number" placeholder="请输入司机编号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="司机姓名">
            <el-input
                      v-model="searchCondition.LIKE_name" placeholder="请输入司机姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系电话">
            <el-input
                      v-model="searchCondition.LIKE_phone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="司机性质">
            <el-select  v-model="searchCondition.EQ_driverProperty" placeholder="请选择司机性质">
              <el-option v-for="item in $store.getters.DRIVER_PROPERTY"
                         :key="item.dictVal"
                         :label="item.cnDictValname"
                         :value="item.dictVal"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </search-bar>

    <!-- 操作 -->
    <el-col :span="24" style="margin-bottom: 10px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" @click="myReset" style="float: right">重置</el-button>
      <el-button type="primary" @click="searchDriverInfos" style="float: right">查询</el-button>
    </el-col>

    <!--列表-->
    <el-table :data="tableData" highlight-current-row border @sort-change="sortChange" max-height="660"
              @selection-change="selsChange" v-loading="listLoading" style="width: 100%;">
      <el-table-column type="index" label="序号" width="80" >
      </el-table-column>
      <el-table-column prop="number" label="司机编号" >
      </el-table-column>
      <el-table-column prop="name" label="司机姓名" width="200" >
      </el-table-column>
      <el-table-column prop="driverProperty" label="司机性质" width="120" >
        <template slot-scope="scope">
          <label v-if="scope.row.driverProperty ===  109012001">自有司机</label>
          <label v-if="scope.row.driverProperty ===  109012002">合作司机</label>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系电话" width="150" >
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="100" >
      </el-table-column>

      <el-table-column prop="drivingAge" label="驾龄" width="100" >
      </el-table-column>

      <el-table-column prop="birthDate" label="出生日期" width="130" >
        <template slot-scope="scope">
          <label v-if="scope.row.birthDate != null">
            {{scope.row.birthDate.toString().substring(0, 10)}}
          </label>
        </template>
      </el-table-column>

      <el-table-column prop="addName" label="添加人" width="150" >
      </el-table-column>

      <el-table-column prop="createDate" label="添加日期" width="150" >
        <template slot-scope="scope">
          <label v-if="scope.row.createDate != null">
            {{scope.row.createDate.toString().substring(0, 10)}}
          </label>
          <label v-else>
            {{scope.row.createdDate.toString().substring(0, 10)}}
          </label>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150">
        <template slot-scope="scope">

          <el-button  type="primary" @click="getEditBYId(scope.$index, scope.row)">编辑 </el-button>
          <el-button type="danger"  @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>

    <!--新增 弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="DrvierVisible" :close-on-click-modal="false">
      <el-form :model="driverInfo" :rules="rules" label-width="80px" ref="driverInfo">
        <el-row>
          <el-col :span="8">
            <el-form-item  label="司机姓名" prop="name">
              <el-input v-model="driverInfo.name" placeholder="请输入司机姓名"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item  label="联系电话" prop="phone" :rules="[
            {required: true, message: '请输入手机号', trigger: 'change'},
            {min:11,max:11, message: '长度在11个字符', trigger: 'change'}
          ]">
              <el-input type="number" v-model="driverInfo.phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item  label="身份证" prop="idNumber">
              <el-input v-model="driverInfo.idNumber" placeholder="请输入身份证号码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row >
          <el-col :span="8">
            <el-form-item  label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="driverInfo.birthDate"
                type="date"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="驾龄" prop="drivingAge"
                          :rules="[{required: true,type:'number', message: '请输入驾龄', trigger: 'change'}]">
              <el-input  type="number" v-model.number="driverInfo.drivingAge"
                        placeholder="请输入驾龄"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="年龄" prop="age" :rules="[
            {required: true,type:'number', message: '请输入年龄', trigger: 'change'}
          ]">
              <el-input  type="number" v-model.number="driverInfo.age"
                        placeholder="请输入年龄"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row >

          <el-col :span="8">
            <el-form-item label="通信地址" prop="address">
              <el-input v-model="driverInfo.address" placeholder="请输入通信地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item  label="隶属机构" prop="currentOrganizationIds">
              <el-cascader
                placeholder="请选择隶属机构"
                :options="$store.state.initOrganizations"
                :props="{label: 'name',value: 'id'}"
                change-on-select
                v-model="driverInfo.currentOrganizationIds"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row >
          <el-col :span="8">
            <el-form-item label="驾驶证号" prop="driverNumber">
              <el-input  v-model="driverInfo.driverNumber"
                        placeholder="请输入驾驶证号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <el-select   v-model="driverInfo.sex"
                         placeholder="请选择">
                <el-option
                  v-for="item in $store.getters.MEMBER_GENDER"
                  :key="item.dictVal"
                  :label="item.cnDictValname"
                  :value="item.dictVal">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="司机性质" prop="driverProperty">
              <el-select  v-model="driverInfo.driverProperty" placeholder="请选择司机性质">
                <el-option v-for="item in $store.getters.DRIVER_PROPERTY"
                :key="item.dictVal"
                :label="item.cnDictValname"
                :value="item.dictVal"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="8">
            <el-form-item label="司机信息">

            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="8">
            <el-form-item label="用户名" prop="account">
              <el-input  v-model="driverInfo.account"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row >
          <el-col :span="8">
            <el-form-item label="密码" prop="password">
              <el-input type="password"  v-model="driverInfo.password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="8">
            <el-form-item label="确认密码" prop="newPassword">
              <el-input type="password"  v-model="driverInfo.newPassword"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="DrvierVisible = false">取消</el-button>
        <el-button type="primary" @click.native="handleSubmit" :loading="submitLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import {
  searchDriverInfo,
  delDriver,
  saveDriverInfo,
  getDriverInfo
} from '../../api/stowage/DriverManage';
import {objToFilter, resetObjNull, isEmpty} from '../../lib/util';
import md5 from 'js-md5';
import {getOrganizationById} from '../../api/organization/Organization';
export default {
  data () {
    return {
      newPassword: '',
      primevalPassword: null,
      searchCondition: {
        LIKE_name: null,
        LIKE_number: null,
        LIKE_phone: null,
        EQ_driverProperty: null
      },

      props1: {
        label: 'name',
        value: 'id',
        children: 'children'
      },

      driverInfoSex: [],
      stowageCoreCenter: [],
      stowageCoreCenter2: [],

      sels: [],
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      sortProp: null,
      sortOrder: 'ascending',
      listLoading: false,
      DrvierVisible: false,
      submitLoading: false,

      dialogTitle: '新增',
      condition: {
        name: '',
        number: ''
      },

      // 表单数据
      driverInfo: {
        currentOrganizationIds: [],
        'id': null,
        'number': null,
        'driverOrganizationId': null,
        'name': null,
        'auditStatus': null,
        'sex': null,
        'birthDate': null,
        'idNumber': null,
        'driverNumber': null,
        'drivingNumber': null,
        'plateNumber': null,
        'drivingAge': null,
        address: null,
        phone: '',
        'account': null,
        'password': null,
        'newPassword': null,
        'avatar': null,
        'email': null,
        'status': null,
        'organizationId': null,
        'remark': null,
        age: '',
        'addName': null,
        'driverProperty': null
      },

      // 验证规则
      rules: {
        currentOrganizationIds: [
          {type: 'array', required: true, message: '请选择隶属机构', trigger: 'change'}
        ],
        name: [
          {required: true, message: '请输入司机姓名', trigger: 'blur'},
          {min: 2, max: 60, message: '长度在2 到 60 个字符', trigger: 'blur'}
        ],
        driverNumber: [
          {required: true, message: '请输入驾驶证号', trigger: 'blur'},
          {min: 18, max: 18, message: '长度在18个字符', trigger: 'blur'}
        ],
        account: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 60, message: '长度在2 到 60 个字符', trigger: 'blur'}
        ],
        sex: [
          {type: 'number', required: true, message: '请选择性别', trigger: 'change'}
        ],
        driverProperty: [
          {type: 'number', required: true, message: '请选择司机性质', trigger: 'change'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 32, message: '长度在6到32 个字符', trigger: 'blur'}
        ],
        newPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 32, message: '长度在6到32 个字符', trigger: 'blur'}
        ],
        idNumber: [
          {required: true, message: '请输入身份证', trigger: 'blur'},
          {min: 18, max: 18, message: '长度在18个字符', trigger: 'blur'}
        ]

      }

    };
  },
  methods: {

    // 搜索 栏重置
    myReset () {
      resetObjNull(this.searchCondition);
    },

    loadingLists (filter) {
      this.listLoading = true;
      searchDriverInfo({
        filters: filter,
        size: this.pageSize,
        page: this.currentPage - 1,
        sorts: (this.sortProp === null ? '' : (this.sortOrder === 'ascending' ? '-' : '+') + this.sortProp)
      }).then(res => {
        if (res.status === 200) {
          this.tableData = res.data;
          this.total = Number(res.headers['x-total-count']);
          this.listLoading = false;
        }
      });
    },

    // 搜索
    searchDriverInfos () {
      this.loadingLists(objToFilter(this.searchCondition));
    },
    // 新增数据提交
    handleSubmit () {
      this.$refs['driverInfo'].validate((valid) => {
        if (valid) {
          if (this.driverInfo.age <= this.driverInfo.drivingAge) {
            return this.$message.error('驾龄不能大于等于年龄，请重新输入！');
          }
          if (this.driverInfo.newPassword !== this.driverInfo.password) {
            return this.$message.error('2次输入的密码不一致，请重新输入！');
          }
          ;
          this.driverInfo.driverOrganizationId = this.driverInfo.currentOrganizationIds.join(',');
          this.submitLoading = true;
          let o = Object.assign({}, this.driverInfo);
          if (isEmpty(o.id) || (!isEmpty(o.id) && o.password !== this.primevalPassword)) {
            o.password = md5(o.password);
          }
          saveDriverInfo(o).then((res) => {
            this.submitLoading = false;
            if (res.status === 201) {
              this.$message.success('保存/修改成功！');
              this.DrvierVisible = false;
              this.searchDriverInfos();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            console.log(error);
          });
        } else {
          return false;
        }
      });
    },

    // 弹出添加窗体
    handleAdd () {
      this.dialogTitle = '新增';
      this.resetForm();
      this.DrvierVisible = true;
    },
    // 打开编辑界面
    getEditBYId (index, row) {
      this.resetForm();
      getDriverInfo(row.id).then((res) => {
        this.driverInfo.newPassword = res.data.password;
        this.primevalPassword = res.data.password;
      });
      this.driverInfo = Object.assign({
        currentOrganizationIds: [],
        'id': null,
        'number': null,
        'name': null,
        'auditStatus': null,
        'sex': null,
        'driverOrganizationId': null,
        'birthDate': null,
        'idNumber': null,
        'driverNumber': null,
        'drivingNumber': null,
        'plateNumber': null,
        'drivingAge': null,
        'address': null,
        phone: '',
        'account': null,
        'password': null,
        'newPassword': null,
        'avatar': null,
        'email': null,
        'status': null,
        'organizationId': null,
        'remark': null,
        age: '',
        'addName': null,
        'driverProperty': null
      }, row);
      if (row.driverOrganizationId && row.driverOrganizationId.length > 0) {
        this.driverInfo.currentOrganizationIds = Object.assign([], row.driverOrganizationId.split(','));
      }
      this.EditTitle = '修改';
      this.DrvierVisible = true;
    },
    // 重置表单
    resetForm () {
      if (this.$refs.driverInfo) {
        this.$refs.driverInfo.resetFields();
      }
      // 当先点击修改，再点击新增，会出现值没有清空,修复处理
      for (let p in this.driverInfo) {
        if (this.driverInfo[p] instanceof Array) {
          this.driverInfo[p] = [];
        } else {
          this.driverInfo[p] = null;
        }
      }
    },

    // 删除单条数据操作
    handleDel (index, row) {
      this.$confirm('确认删除该司机吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        delDriver(row.id).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.searchDriverInfos();
        });
      }).catch(() => {
      });
    },

    // 多选操作
    selsChange (sels) {
      this.sels = sels;
    },
    // 排序操作
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.searchDriverInfos();
    },
    // 每页几条操作
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchDriverInfos();
    },
    // 第几页操作
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchDriverInfos();
    },
    getTableData () {
      this.listLoading = true;
      searchDriverInfo({
        filters: '',
        sorts: '',
        page: this.currentPage,
        size: this.pageSize
      }).then((res) => {
        this.listLoading = false;
        if (res.data.successFlg) {
          this.tableData = res.data.detailModelList;
          this.currentPage = res.data.currPage;
          this.total = res.data.totalCount;
          this.pageSize = res.data.pageSize;
          this.listLoading = false;
        } else {
          this.$message.error(res.data.errorMsg);
        }
      });
    }
  },
  mounted () {
    getOrganizationById(this.$store.state.currentOrganizationId).then(res => {
      if (res.data.successFlg) {
        if (res.data.obj) {
          let ids = Object.assign([], res.data.obj.pids);
          ids.push(res.data.obj.id);
          this.driverInfo.currentOrganizationIds = Object.assign([], ids);
        } else {
          this.driverInfo.currentOrganizationIds = [];
        }
      }
    });
    this.getTableData();
    //  this.searchOrganizations();
    this.$store.commit('initOrganizations');
    this.searchDriverInfos();
    this.$store.commit('initDict');
  }
};
</script>

<style lang="less">

</style>
